﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VidGrab;
using System.Drawing;
using System.IO;
using System.Diagnostics;
using System.Threading;
using VideoLink.Frames;

namespace VideoLink.Streams
{
    /// <summary>
    /// Приёмник видео, основанный на контроле TVideoGrabber.
    /// Работает медленнее, чем ByFrameJPEGReceiver, поэтому не используется.
    /// </summary>
    public class ByFrameTVGReceiver : VideoReceiverBase
    {
        /// <summary>
        /// Очередь кадров
        /// </summary>
        private Queue<VideoStreamInfo> framesQueue;

        /// <summary>
        /// Контрол, отображающий видео
        /// </summary>
        protected VideoGrabber videoGrabber;

        /// <summary>
        /// Создать новый экземпляр класса с указанным ID потока
        /// </summary>
        /// <param name="streamID">
        /// ID потока, уникален для каждого потока
        /// </param>
        public ByFrameTVGReceiver(int streamID)
            : base(streamID)
        {
            InitializeComponent();
            framesQueue = new Queue<VideoStreamInfo>();
            videoGrabber.VideoSource = TVideoSource.vs_JPEGsOrBitmaps;
            videoGrabber.FrameRate = 25;
            videoGrabber.OnVideoFromBitmapsNextFrameNeeded += 
                new OnVideoFromBitmapsNextFrameNeededEventHandler(videoGrabber_OnVideoFromBitmapsNextFrameNeeded);
        }

        /// <summary>
        /// Создать новый экземпляр класса по полученной информации о потоке
        /// </summary>
        /// <param name="stream">
        /// Информация о потоке, который будет приниматься данным экземпляром
        /// </param>
        public ByFrameTVGReceiver(VideoStreamInfo stream)
            : this(stream.StreamID)
        {
            framesQueue.Enqueue(stream);
        }

        #region Component

        /// <summary>
        /// Дизайнер
        /// </summary>
        private void InitializeComponent()
        {
            this.videoGrabber = new VideoGrabber();
            this.ViewportPanel.Controls.Add(videoGrabber);
            // 
            // videoGrabber
            // 
            this.videoGrabber.Dock = System.Windows.Forms.DockStyle.Fill;
            this.videoGrabber.AdjustPixelAspectRatio = true;
            this.videoGrabber.AnalogVideoStandard = -1;
            this.videoGrabber.ApplicationPriority = VidGrab.TApplicationPriority.ap_default;
            this.videoGrabber.ASFAudioBitRate = -1;
            this.videoGrabber.ASFAudioChannels = -1;
            this.videoGrabber.ASFDeinterlaceMode = VidGrab.TASFDeinterlaceMode.adm_NotInterlaced;
            this.videoGrabber.ASFFixedFrameRate = false;
            this.videoGrabber.ASFMediaServerPublishingPoint = "";
            this.videoGrabber.ASFMediaServerRemovePublishingPointAfterDisconnect = false;
            this.videoGrabber.ASFMediaServerTemplatePublishingPoint = "";
            this.videoGrabber.ASFNetworkMaxUsers = 5;
            this.videoGrabber.ASFNetworkPort = 0;
            this.videoGrabber.ASFProfile = -1;
            this.videoGrabber.ASFProfileFromCustomFile = "";
            this.videoGrabber.ASFProfileVersion = VidGrab.TASFProfileVersion.apv_ProfileVersion_8;
            this.videoGrabber.ASFVideoBitRate = -1;
            this.videoGrabber.ASFVideoFrameRate = 0;
            this.videoGrabber.ASFVideoHeight = -1;
            this.videoGrabber.ASFVideoMaxKeyFrameSpacing = -1;
            this.videoGrabber.ASFVideoQuality = -1;
            this.videoGrabber.ASFVideoWidth = -1;
            this.videoGrabber.AssociateAudioAndVideoDevices = false;
            this.videoGrabber.AudioBalance = 0;
            this.videoGrabber.AudioCompressor = 0;
            this.videoGrabber.AudioDevice = -1;
            this.videoGrabber.AudioDeviceRendering = false;
            this.videoGrabber.AudioFormat = VidGrab.TAudioFormat.af_default;
            this.videoGrabber.AudioInput = -1;
            this.videoGrabber.AudioInputBalance = 0;
            this.videoGrabber.AudioInputLevel = 50000;
            this.videoGrabber.AudioInputMono = false;
            this.videoGrabber.AudioPeakEvent = false;
            this.videoGrabber.AudioRecording = false;
            this.videoGrabber.AudioRenderer = -1;
            this.videoGrabber.AudioSource = VidGrab.TAudioSource.as_Default;
            this.videoGrabber.AudioStreamNumber = -1;
            this.videoGrabber.AudioSyncAdjustment = 0;
            this.videoGrabber.AudioSyncAdjustmentEnabled = false;
            this.videoGrabber.AudioVolume = 32767;
            this.videoGrabber.AutoConnectRelatedPins = true;
            this.videoGrabber.AutoFileName = VidGrab.TAutoFileName.fn_Sequential;
            this.videoGrabber.AutoFileNameMinDigits = 6;
            this.videoGrabber.AutoFilePrefix = "vg";
            this.videoGrabber.AutoRefreshPreview = false;
            this.videoGrabber.AutoStartPlayer = true;
            this.videoGrabber.AVIDurationUpdated = true;
            this.videoGrabber.AVIFormatOpenDML = true;
            this.videoGrabber.AVIFormatOpenDMLCompatibilityIndex = true;
            this.videoGrabber.BackColor = System.Drawing.Color.DarkGray;
            this.videoGrabber.BackgroundColor = 0;
            this.videoGrabber.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.videoGrabber.BufferCount = -1;
            this.videoGrabber.BurstCount = 3;
            this.videoGrabber.BurstInterval = 0;
            this.videoGrabber.BurstMode = false;
            this.videoGrabber.BurstType = VidGrab.TFrameCaptureDest.fc_TBitmap;
            this.videoGrabber.BusyCursor = VidGrab.TCursors.cr_HourGlass;
            this.videoGrabber.CameraControlSettings = true;
            this.videoGrabber.CaptureFileExt = "";
            this.videoGrabber.ColorKey = 1048592;
            this.videoGrabber.ColorKeyEnabled = false;
            this.videoGrabber.CompressionMode = VidGrab.TCompressionMode.cm_NoCompression;
            this.videoGrabber.CompressionType = VidGrab.TCompressionType.ct_Video;
            this.videoGrabber.Cropping_Enabled = false;
            this.videoGrabber.Cropping_Height = 120;
            this.videoGrabber.Cropping_Outbounds = true;
            this.videoGrabber.Cropping_Width = 160;
            this.videoGrabber.Cropping_X = 0;
            this.videoGrabber.Cropping_Y = 0;
            this.videoGrabber.Cropping_Zoom = 1;
            this.videoGrabber.Display_Active = true;
            this.videoGrabber.Display_AspectRatio = VidGrab.TAspectRatio.ar_Stretch;
            this.videoGrabber.Display_AutoSize = false;
            this.videoGrabber.Display_Embedded = true;
            this.videoGrabber.Display_FullScreen = false;
            this.videoGrabber.Display_Height = 240;
            this.videoGrabber.Display_Left = 10;
            this.videoGrabber.Display_Monitor = 0;
            this.videoGrabber.Display_MouseMovesWindow = true;
            this.videoGrabber.Display_PanScanRatio = 50;
            this.videoGrabber.Display_StayOnTop = false;
            this.videoGrabber.Display_Top = 10;
            this.videoGrabber.Display_VideoPortEnabled = true;
            this.videoGrabber.Display_Visible = true;
            this.videoGrabber.Display_Width = 320;
            this.videoGrabber.DoubleBuffered = false;
            this.videoGrabber.DroppedFramesPollingInterval = -1;
            this.videoGrabber.DualDisplay_Active = false;
            this.videoGrabber.DualDisplay_AspectRatio = VidGrab.TAspectRatio.ar_Stretch;
            this.videoGrabber.DualDisplay_AutoSize = false;
            this.videoGrabber.DualDisplay_Embedded = false;
            this.videoGrabber.DualDisplay_FullScreen = false;
            this.videoGrabber.DualDisplay_Height = 240;
            this.videoGrabber.DualDisplay_Left = 400;
            this.videoGrabber.DualDisplay_Monitor = 0;
            this.videoGrabber.DualDisplay_MouseMovesWindow = true;
            this.videoGrabber.DualDisplay_PanScanRatio = 50;
            this.videoGrabber.DualDisplay_StayOnTop = false;
            this.videoGrabber.DualDisplay_Top = 20;
            this.videoGrabber.DualDisplay_VideoPortEnabled = false;
            this.videoGrabber.DualDisplay_Visible = true;
            this.videoGrabber.DualDisplay_Width = 320;
            this.videoGrabber.DVDateTimeEnabled = true;
            this.videoGrabber.DVDiscontinuityMinimumInterval = 3;
            this.videoGrabber.DVDTitle = 0;
            this.videoGrabber.DVEncoder_VideoFormat = VidGrab.TDVVideoFormat.dvf_DVSD;
            this.videoGrabber.DVEncoder_VideoResolution = VidGrab.TDVSize.dv_Full;
            this.videoGrabber.DVEncoder_VideoStandard = VidGrab.TDVVideoStandard.dvs_Default;
            this.videoGrabber.DVRecordingInNativeFormatSeparatesStreams = false;
            this.videoGrabber.DVReduceFrameRate = false;
            this.videoGrabber.DVRgb219 = false;
            this.videoGrabber.DVTimeCodeEnabled = true;
            this.videoGrabber.EventNotificationSynchrone = true;
            this.videoGrabber.FixFlickerOrBlackCapture = false;
            this.videoGrabber.FrameCaptureHeight = -1;
            this.videoGrabber.FrameCaptureWidth = -1;
            this.videoGrabber.FrameCaptureWithoutOverlay = false;
            this.videoGrabber.FrameCaptureZoomSize = 100;
            this.videoGrabber.FrameGrabber = VidGrab.TFrameGrabber.fg_BothStreams;
            this.videoGrabber.FrameGrabberRGBFormat = VidGrab.TFrameGrabberRGBFormat.fgf_Default;
            this.videoGrabber.FrameRate = 0;
            this.videoGrabber.HoldRecording = false;
            this.videoGrabber.ImageOverlay_AlphaBlend = false;
            this.videoGrabber.ImageOverlay_AlphaBlendValue = 180;
            this.videoGrabber.ImageOverlay_ChromaKey = false;
            this.videoGrabber.ImageOverlay_ChromaKeyLeewayPercent = 25;
            this.videoGrabber.ImageOverlay_ChromaKeyRGBColor = 0;
            this.videoGrabber.ImageOverlay_Height = -1;
            this.videoGrabber.ImageOverlay_LeftLocation = 10;
            this.videoGrabber.ImageOverlay_StretchToVideoSize = false;
            this.videoGrabber.ImageOverlay_TopLocation = 10;
            this.videoGrabber.ImageOverlay_Transparent = false;
            this.videoGrabber.ImageOverlay_TransparentColorValue = 0;
            this.videoGrabber.ImageOverlay_UseTransparentColor = false;
            this.videoGrabber.ImageOverlay_Width = -1;
            this.videoGrabber.ImageOverlayEnabled = false;
            this.videoGrabber.ImageOverlaySelector = 0;
            this.videoGrabber.IPCameraURL = "";
            this.videoGrabber.JPEGPerformance = VidGrab.TJPEGPerformance.jpBestQuality;
            this.videoGrabber.JPEGProgressiveDisplay = false;
            this.videoGrabber.JPEGQuality = 100;
            this.videoGrabber.LicenseString = "N/A";
            this.videoGrabber.Location = new System.Drawing.Point(0, 0);
            this.videoGrabber.LogoDisplayed = false;
            this.videoGrabber.LogoLayout = VidGrab.TLogoLayout.lg_Stretched;
            this.videoGrabber.MixAudioSamples_CurrentSourceLevel = 100;
            this.videoGrabber.MixAudioSamples_ExternalSourceLevel = 100;
            this.videoGrabber.Mixer_MosaicColumns = 1;
            this.videoGrabber.Mixer_MosaicLines = 1;
            this.videoGrabber.MotionDetector_CompareBlue = true;
            this.videoGrabber.MotionDetector_CompareGreen = true;
            this.videoGrabber.MotionDetector_CompareRed = true;
            this.videoGrabber.MotionDetector_Enabled = false;
            this.videoGrabber.MotionDetector_GreyScale = false;
            this.videoGrabber.MotionDetector_Grid = "5555555555 5555555555 5555555555 5555555555 5555555555 5555555555 5555555555 5555" +
                "555555 5555555555 5555555555 ";
            this.videoGrabber.MotionDetector_MaxDetectionsPerSecond = 0;
            this.videoGrabber.MotionDetector_ReduceCPULoad = 1;
            this.videoGrabber.MotionDetector_ReduceVideoNoise = false;
            this.videoGrabber.MotionDetector_Triggered = false;
            this.videoGrabber.MouseWheelEventEnabled = false;
            this.videoGrabber.MpegStreamType = VidGrab.TMpegStreamType.mpst_Default;
            this.videoGrabber.MultiplexedInputEmulation = true;
            this.videoGrabber.MultiplexedRole = VidGrab.TMultiplexedRole.mr_NotMultiplexed;
            this.videoGrabber.MultiplexedStabilizationDelay = 4;
            this.videoGrabber.MultiplexedSwitchDelay = 0;
            this.videoGrabber.MuteAudioRendering = false;
            this.videoGrabber.Name = "videoGrabber";
            this.videoGrabber.NetworkStreaming = VidGrab.TNetworkStreaming.ns_Disabled;
            this.videoGrabber.NetworkStreamingType = VidGrab.TNetworkStreamingType.nst_AudioVideoStreaming;
            this.videoGrabber.NormalCursor = VidGrab.TCursors.cr_Default;
            this.videoGrabber.NotificationMethod = VidGrab.TNotificationMethod.nm_Thread;
            this.videoGrabber.NotificationPriority = VidGrab.TThreadPriority.tpNormal;
            this.videoGrabber.NotificationSleepTime = -1;
            this.videoGrabber.OverlayAfterTransform = false;
            this.videoGrabber.PlayerAudioRendering = true;
            this.videoGrabber.PlayerDuration = ((long)(1));
            this.videoGrabber.PlayerDVSize = VidGrab.TDVSize.dv_Full;
            this.videoGrabber.PlayerFastSeekSpeedRatio = 4;
            this.videoGrabber.PlayerFileName = "";
            this.videoGrabber.PlayerForcedCodec = "";
            this.videoGrabber.PlayerFramePosition = ((long)(0));
            this.videoGrabber.PlayerRefreshPausedDisplay = false;
            this.videoGrabber.PlayerRefreshPausedDisplayFrameRate = 0;
            this.videoGrabber.PlayerSpeedRatio = 1;
            this.videoGrabber.PlayerTimePosition = ((long)(0));
            this.videoGrabber.PlayerTrackBarSynchrone = false;
            this.videoGrabber.PlaylistIndex = 0;
            this.videoGrabber.PreallocCapFileCopiedAfterRecording = true;
            this.videoGrabber.PreallocCapFileEnabled = false;
            this.videoGrabber.PreallocCapFileName = "";
            this.videoGrabber.PreallocCapFileSizeInMB = 100;
            this.videoGrabber.PreviewZoomSize = 100;
            this.videoGrabber.RawAudioSampleCapture = false;
            this.videoGrabber.RawCaptureAsyncEvent = true;
            this.videoGrabber.RawSampleCaptureLocation = VidGrab.TRawSampleCaptureLocation.rl_SourceFormat;
            this.videoGrabber.RawVideoSampleCapture = false;
            this.videoGrabber.RecordingBacktimedFramesCount = 0;
            this.videoGrabber.RecordingCanPause = false;
            this.videoGrabber.RecordingFileName = "";
            this.videoGrabber.RecordingInNativeFormat = true;
            this.videoGrabber.RecordingMethod = VidGrab.TRecordingMethod.rm_AVI;
            this.videoGrabber.RecordingOnMotion_Enabled = false;
            this.videoGrabber.RecordingOnMotion_MotionThreshold = 0;
            this.videoGrabber.RecordingOnMotion_NoMotionPauseDelayMs = 5000;
            this.videoGrabber.RecordingPauseCreatesNewFile = false;
            this.videoGrabber.RecordingSize = VidGrab.TRecordingSize.rs_Default;
            this.videoGrabber.RecordingTimer = VidGrab.TRecordingTimer.rt_Disabled;
            this.videoGrabber.RecordingTimerInterval = 0;
            this.videoGrabber.Reencoding_IncludeAudioStream = true;
            this.videoGrabber.Reencoding_IncludeVideoStream = true;
            this.videoGrabber.Reencoding_Method = VidGrab.TRecordingMethod.rm_AVI;
            this.videoGrabber.Reencoding_NewVideoClip = "";
            this.videoGrabber.Reencoding_SourceVideoClip = "";
            this.videoGrabber.Reencoding_StartFrame = ((long)(-1));
            this.videoGrabber.Reencoding_StartTime = ((long)(-1));
            this.videoGrabber.Reencoding_StopFrame = ((long)(-1));
            this.videoGrabber.Reencoding_StopTime = ((long)(-1));
            this.videoGrabber.Reencoding_UseAudioCompressor = false;
            this.videoGrabber.Reencoding_UseFrameGrabber = true;
            this.videoGrabber.Reencoding_UseVideoCompressor = false;
            this.videoGrabber.Reencoding_WMVOutput = false;
            this.videoGrabber.ScreenRecordingMonitor = 0;
            this.videoGrabber.ScreenRecordingNonVisibleWindows = false;
            this.videoGrabber.ScreenRecordingThroughClipboard = false;
            this.videoGrabber.ScreenRecordingWithCursor = true;
            this.videoGrabber.SendToDV_DeviceIndex = -1;
            this.videoGrabber.Size = new System.Drawing.Size(320, 240);
            this.videoGrabber.SpeakerBalance = 0;
            this.videoGrabber.SpeakerControl = false;
            this.videoGrabber.SpeakerVolume = 32767;
            this.videoGrabber.StoragePath = "c:\\0_MyFiles\\programming\\Projects\\SmartLink\\VideoLink\\VideoLink";
            this.videoGrabber.StoreDeviceSettingsInRegistry = false;
            this.videoGrabber.SyncCommands = true;
            this.videoGrabber.SynchronizationRole = VidGrab.TSynchronizationRole.sr_Master;
            this.videoGrabber.Synchronized = false;
            this.videoGrabber.SyncPreview = VidGrab.TSyncPreview.sp_Auto;
            this.videoGrabber.TabIndex = 0;
            this.videoGrabber.TextOverlay_Align = VidGrab.TTextOverlayAlign.tf_Left;
            this.videoGrabber.TextOverlay_BkColor = 16777215;
            this.videoGrabber.TextOverlay_Enabled = false;
            this.videoGrabber.TextOverlay_Font = 101326458;
            this.videoGrabber.TextOverlay_FontColor = 16776960;
            this.videoGrabber.TextOverlay_Left = 0;
            this.videoGrabber.TextOverlay_Right = 1000;
            this.videoGrabber.TextOverlay_ScrollingSpeed = 0;
            this.videoGrabber.TextOverlay_Selector = 0;
            this.videoGrabber.TextOverlay_Shadow = true;
            this.videoGrabber.TextOverlay_ShadowColor = 0;
            this.videoGrabber.TextOverlay_ShadowDirection = VidGrab.TCardinalDirection.cd_NorthWest;
            this.videoGrabber.TextOverlay_String = "Example of static text (TextOverlay_Selector=0). Set TextOverlay_Selector=1 to se" +
                "e a demo with variables.";
            this.videoGrabber.TextOverlay_Top = 0;
            this.videoGrabber.TextOverlay_Transparent = true;
            this.videoGrabber.TranslateMouseCoordinates = true;
            this.videoGrabber.TunerFrequency = -1;
            this.videoGrabber.TunerMode = VidGrab.TTunerMode.tm_TVTuner;
            this.videoGrabber.TVChannel = 0;
            this.videoGrabber.TVCountryCode = 0;
            this.videoGrabber.TVTunerInputType = VidGrab.TTunerInputType.TunerInputCable;
            this.videoGrabber.TVUseFrequencyOverrides = false;
            this.videoGrabber.UseClock = true;
            this.videoGrabber.VCRHorizontalLocking = false;
            this.videoGrabber.Version = "v7.6 build 7.6.215.3 - March 3, 2009 (76.214) - Copyright ©2002-2008 Datastead";
            this.videoGrabber.VideoCompression_DataRate = -1;
            this.videoGrabber.VideoCompression_KeyFrameRate = 15;
            this.videoGrabber.VideoCompression_PFramesPerKeyFrame = 0;
            this.videoGrabber.VideoCompression_Quality = 1;
            this.videoGrabber.VideoCompression_WindowSize = -1;
            this.videoGrabber.VideoCompressor = 0;
            this.videoGrabber.VideoControlSettings = true;
            this.videoGrabber.VideoCursor = VidGrab.TCursors.cr_Default;
            this.videoGrabber.VideoDevice = -1;
            this.videoGrabber.VideoFormat = -1;
            this.videoGrabber.VideoFromImages_BitmapsSortedBy = VidGrab.TFileSort.fs_TimeAsc;
            this.videoGrabber.VideoFromImages_RepeatIndefinitely = false;
            this.videoGrabber.VideoFromImages_SourceDirectory = "c:\\0_MyFiles\\programming\\Projects\\SmartLink\\VideoLink\\VideoLink";
            this.videoGrabber.VideoFromImages_TemporaryFile = "SetOfBitmaps01.dat";
            this.videoGrabber.VideoInput = -1;
            this.videoGrabber.VideoProcessing_Brightness = 0;
            this.videoGrabber.VideoProcessing_Contrast = 0;
            this.videoGrabber.VideoProcessing_Deinterlacing = VidGrab.TVideoDeinterlacing.di_Disabled;
            this.videoGrabber.VideoProcessing_FlipHorizontal = false;
            this.videoGrabber.VideoProcessing_FlipVertical = false;
            this.videoGrabber.VideoProcessing_GrayScale = false;
            this.videoGrabber.VideoProcessing_Hue = 0;
            this.videoGrabber.VideoProcessing_InvertColors = false;
            this.videoGrabber.VideoProcessing_Pixellization = 1;
            this.videoGrabber.VideoProcessing_Rotation = VidGrab.TVideoRotation.rt_0_deg;
            this.videoGrabber.VideoProcessing_RotationCustomAngle = 45.5;
            this.videoGrabber.VideoProcessing_Saturation = 0;
            this.videoGrabber.VideoQualitySettings = true;
            this.videoGrabber.VideoRenderer = VidGrab.TVideoRenderer.vr_AutoSelect;
            this.videoGrabber.VideoRendererExternal = VidGrab.TVideoRendererExternal.vre_None;
            this.videoGrabber.VideoSize = -1;
            this.videoGrabber.VideoSource = VidGrab.TVideoSource.vs_VideoCaptureDevice;
            this.videoGrabber.VideoSource_FileOrURL = "";
            this.videoGrabber.VideoSource_FileOrURL_StartTime = ((long)(-1));
            this.videoGrabber.VideoSource_FileOrURL_StopTime = ((long)(-1));
            this.videoGrabber.VideoSubtype = -1;
            this.videoGrabber.VideoVisibleWhenStopped = false;
            this.videoGrabber.VirtualAudioStreamControl = -1;
            this.videoGrabber.VirtualVideoStreamControl = -1;
            this.videoGrabber.VuMeter = VidGrab.TVuMeter.vu_Disabled;
            this.videoGrabber.ZoomCoeff = 1000;
            this.videoGrabber.ZoomXCenter = 0;
            this.videoGrabber.ZoomYCenter = 0;
        }

        #endregion
        
        #region Public Methods

        /// <summary>
        /// Обработать новый, только что полученный, кадр.
        /// Данная реализация ставит кадр в очередь.
        /// </summary>
        /// <param name="frame">Кадр</param>
        public override void NewFrameReceived(VideoStreamInfo frame)
        {
            base.NewFrameReceived(frame);

            switch (frame.State)
            { 
                case VideoStreamState.Play:
                    framesQueue.Enqueue(frame);
                    Debug.WriteLine("+ " + framesQueue.Count.ToString());
                    videoGrabber.StartPreview();
                    break;
                case VideoStreamState.Stop:
                    videoGrabber.Stop();
                    break;
                case VideoStreamState.Pause:
                    videoGrabber.PausePreview();
                    break;
            }
            State = frame.State;
        }
        
        #endregion

        #region Private Methods

        /// <summary>
        /// Вызывается videoGrabber'ом, когда ему нужен следующий кадр для воспроизведения
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void videoGrabber_OnVideoFromBitmapsNextFrameNeeded(object sender, TOnVideoFromBitmapsNextFrameNeededEventArgs e)
        {
            if (framesQueue.Count > 1)
            {
                framesQueue.Dequeue();
            }

            Debug.WriteLine("-");
            var bmp = (framesQueue.Peek().Value as OneFrame).Image;
            videoGrabber.SendImageToVideoFromBitmaps(string.Empty,
                bmp.GetHbitmap().ToInt32(),
                true,
                true);
        }
        
        #endregion
    }
}
